package com.pie4cloud.pie.job.api.consumer;


import com.pie4cloud.pie.common.core.constant.SecurityConstants;
import com.pie4cloud.pie.common.core.util.R;
import com.pie4cloud.pie.common.security.annotation.Inner;
import com.pie4cloud.pie.job.api.consumer.factory.IHanlderFactory;
import com.pie4cloud.pie.job.api.dto.CallBackDto;
import com.pie4cloud.pie.job.api.dto.TriggerParam;
import com.pie4cloud.pie.job.api.feign.RemoteCallBackService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController()
@RequestMapping("/job")
@RequiredArgsConstructor
@Api(value = "job", tags = "远程调用")
public class HanlderController {
	private final RemoteCallBackService remoteCallBackService;
    @Autowired
	private IHanlderFactory iHanlderFactory;

	/*private ThreadPoolExecutor pool = new ThreadPoolExecutor(10, // corSize
            1000, // maxPoolSize
			60, // keepAliveTime
			TimeUnit.SECONDS, // unit,
			new ArrayBlockingQueue(50),// workQueue
			new ThreadPoolExecutor.AbortPolicy()

	);*/
	private ThreadPoolExecutor pool = new ThreadPoolExecutor(50, 1000, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

	@Inner
	@PostMapping("/execute")
	public R execute(@RequestBody TriggerParam triggerParam) {
		try {
			pool.execute(()->{
				CallBackDto callBackDto=new CallBackDto();
				callBackDto.setType(triggerParam.getType());
				try {
					IHanlderConsumer iHanlderConsumer= iHanlderFactory.get(triggerParam.getHanlder());
					iHanlderConsumer.execute(triggerParam.getParams(),callBackDto);
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					//remoteCallBackService.execute(callBackDto, SecurityConstants.FROM_IN);
				}
			});
		} catch (Exception e) {
			return R.failed();
		}

		return R.ok();
	}
}
